from contextlib import asynccontextmanager

from tortoise import connections
from tortoise.contrib.fastapi import register_tortoise
from fastapi import FastAPI

db_config = {
    "connections": {
        "default": {
            "engine": "tortoise.backends.mysql",  # 要连接数据库的类型 mysql
            "credentials": {  # 登录凭证  就是数据库的相关信息
                "host": "localhost",
                "port": 3306,
                "user": "root",
                "password": "root",
                "database": "ruoyi-fastapi",
            },
        },
    },
    "apps": {
        "models": {  # 当前数据库前缀 ,在数据模型的类中 可能会用到
            "models": ["modules.domain.dept", ],  # 要加载的模型类
            "default_connection": "default",  # 需要使用哪个配置连接相对应得数据库
        },
    },
    "use_tz": False,  # 不适用默认时区
    "timezone": "Asia/Shanghai",  # 设置上海时区
    "logging": {
        "level": "DEBUG",  # 日志级别
        "handlers": {
            "default": {
                "class": "logging.StreamHandler",
                "formatter": "default",
                "stream": "ext://sys.stdout",
            },
        },
    }
}


# 我们采用的是异步上下文管理器来初始化数据库连接
@asynccontextmanager
async def init_database(app: FastAPI):
    try:
        async with register_tortoise(
            app,
            config=db_config,
            generate_schemas=True,  # 自动生成数据库表结构
            add_exception_handlers=True,
        ):
            yield print("=================== Database MySQL  连接成功 ===================")
            #
            await connections.close_all()
            print("=================== Database MySQL  连接关闭 ===================")
    except Exception as e:
        print(f"Error connecting to database: {e}")
        raise e


def init_db(app: FastAPI):
    register_tortoise(
            app,
            config=db_config,
            generate_schemas=True,  # 自动生成数据库表结构
            add_exception_handlers=True,
        )